package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Constants;
import com.example.common.HttpStatusEnum;
import com.example.common.codeFactory.CodeGenerateStrategy;
import com.example.common.codeFactory.CodeGenerateStrategyFactory;
import com.example.common.codeFactory.entity.CodeGenerateType;
import com.example.config.ConfigTableValueConfig;
import com.example.entity.ResponseData;
import com.example.entity.SelectOptionsList;
import com.example.entity.TreeOptions;
import com.example.pojo.Enterprise;
import com.example.mapper.EnterpriseMapper;
import com.example.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 组织单位表(Enterprise)表服务实现类
 *
 * @email: pengyujun53@163.com
 * @author: peng_YuJun
 * @date: 2024/01/17
 * @time: 23:13
 */
@Service
public class EnterpriseService{
    /**
     * mapper对象 
     */
    @Resource
    private EnterpriseMapper enterpriseMapper;
    // 系统配置参数
    @Resource
    private ConfigTableValueConfig configValue;
    // 编号工厂
    @Resource
    private CodeGenerateStrategyFactory codeGenerateStrategyFactory;
    
    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param enterprise 筛选条件
     * @return
     */
    public ResponseData getByPage(Integer currentPage, Integer pageSize, Enterprise enterprise) {
        //查询条件构建
        LambdaQueryWrapper<Enterprise> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.hasText(enterprise.getParent()), Enterprise::getParent, enterprise.getParent());
        lqw.like(StringUtils.hasText(enterprise.getCode()), Enterprise::getCode, enterprise.getCode());
        lqw.like(StringUtils.hasText(enterprise.getTitle()), Enterprise::getTitle, enterprise.getTitle());
        lqw.eq(!Arrays.asList(-1, null).contains(enterprise.getDeleted()), Enterprise::getDeleted, enterprise.getDeleted());
        //查询
        IPage ipage = new Page(currentPage,pageSize);
        enterpriseMapper.selectPage(ipage,lqw);
        //若当前页码大于总页面数
        if (currentPage > ipage.getPages()){
            ipage = new Page(ipage.getPages(),pageSize);
            enterpriseMapper.selectPage(ipage,lqw);
        }
        if (ipage.getTotal()<=0){
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(),ipage);
    }
    
    /**
     * 根据ID查询信息
     *
     * @param id 主键
     * @return 单条数据
     */
    public ResponseData findById(Long id) {
        Enterprise enterprise = enterpriseMapper.selectById(id);
        if(enterprise == null || enterprise.getId() == null){
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        //返回结果
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(),enterprise);
    }
    
    /**
     * 新增数据
     *
     * @param  enterprise 实体
     * @return 新增结果
     */
    public ResponseData add(MultipartFile file, Enterprise enterprise) {
        if (FileUtil.isMultipartFile(file)){
            //保存图片
            String pic = FileUtil.storeFile(file, configValue.getEntPhotosStorePath(), false);
            if (StringUtils.hasText(pic)){
                enterprise.setPhotos(configValue.getEntPhotosNetUrl()  + Constants.FORWARD_SLASH + pic);
            }
        }
        //插入
        if (enterpriseMapper.insert(enterprise)>0){
            // 插入成功后要赋值编码
            CodeGenerateStrategy codeGenerateStrategy = codeGenerateStrategyFactory.getCodeGenerateStrategy(CodeGenerateType.ENT);
            String codePrefix = enterprise.getParent().equals("-1") ? "" : enterprise.getParent();
            enterprise.setCode(codeGenerateStrategy.generateCode(codePrefix, enterprise.getId().intValue()));
            enterpriseMapper.updateById(enterprise);
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "新增失败，请稍后再试");
    }
    
    /**
     * 更新数据
     *
     * @param enterprise 实体
     * @return 更新结果
     */
    public ResponseData update(MultipartFile file, Enterprise enterprise) {
        //替换图片
        if (FileUtil.isMultipartFile(file)){
            String pic = FileUtil.storeFile(file, configValue.getEntPhotosStorePath(), false);
            if (StringUtils.hasText(pic)){
                enterprise.setPhotos(configValue.getEntPhotosNetUrl()  + Constants.FORWARD_SLASH + pic);
                // 删除原来的
                Enterprise enterpriseTemp = enterpriseMapper.selectById(enterprise.getId());
                FileUtil.deleteFile(configValue.getEntPhotosStorePath() + File.separator,
                        enterpriseTemp.getPhotos().replace(configValue.getEntPhotosNetUrl()  + Constants.FORWARD_SLASH, ""));
            }
        }
        // 更新的时候需要关注code的更新，这里默认都重新赋值
        CodeGenerateStrategy codeGenerateStrategy = codeGenerateStrategyFactory.getCodeGenerateStrategy(CodeGenerateType.ENT);
        String codePrefix = enterprise.getParent().equals("-1") ? "" : enterprise.getParent();
        enterprise.setCode(codeGenerateStrategy.generateCode(codePrefix, enterprise.getId().intValue()));
        //更新
        if (enterpriseMapper.updateById(enterprise)>0){
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "修改失败，请稍后再试");
    }
    
    /**
     * 删除数据
     *
     * @param id 主键
     * @return 
     */
    public ResponseData delete(Long id) {
        if (enterpriseMapper.deleteById(id)>0){
            //返回成功响应
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "删除失败，请稍后再试");
    }
    
    /**
     * 批量删除
     * @param idList
     * @return
     */
    public ResponseData deleteBatch(List<Long> idList){
        if (enterpriseMapper.deleteBatchIds(idList)>0){
            //返回成功响应
            return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage());
        }
        return new ResponseData(HttpStatusEnum.ERROR.getCode(), "删除失败，请稍后再试");
    }

    /**
     * 树形缩进选项列表查询
     * @param parent
     * @param deleted
     * @return
     */
    public ResponseData getIndentOptions(String parent, Integer deleted) {
        // 查询
        List<TreeOptions> treeOptions = enterpriseMapper.selectTreeOptions(parent, deleted);
        // 整理成带缩进的列表
        SelectOptionsList optionsList = new SelectOptionsList();
        optionsList.makeIndentOptions(treeOptions);
        List<Map> menuOptions = optionsList.getIndentOptionsList();
        if (menuOptions == null || menuOptions.isEmpty()) {
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        //返回结果
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), menuOptions);
    }

    /**
     * 获取所有有效科室单位
     * @return
     */
    public ResponseData getAllValidDrEnt() {
        // 查询
        LambdaQueryWrapper<Enterprise> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Enterprise::getParent, "ent0003");
        lqw.eq(Enterprise::getDeleted, 0);
        List<Enterprise> enterprises = enterpriseMapper.selectList(lqw);
        // 返回结果
        if (enterprises == null || enterprises.isEmpty()){
            return new ResponseData(HttpStatusEnum.DATA_NOT_EXIST.getCode(), HttpStatusEnum.DATA_NOT_EXIST.getMessage());
        }
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), enterprises);
    }

    /**
     * 查询学院和专业列表的数据
     * @return
     */
    public ResponseData getAllStuEnt() {
        LambdaQueryWrapper<Enterprise> lqw = new LambdaQueryWrapper<>();
        // 查找学院机构
        lqw.eq(Enterprise::getParent, "ent0014");
        List<Enterprise> collegeEnt = enterpriseMapper.selectList(lqw);
        List<String> parentCodes = collegeEnt.stream()
                .map(Enterprise::getCode)
                .collect(Collectors.toList());
        // 查找专业机构
        lqw.clear();
        lqw.in(Enterprise::getParent, parentCodes);
        List<Enterprise> majorEnt = enterpriseMapper.selectList(lqw);
        // 组成map
        Map<String, Object> result = new HashMap<>();
        result.put("collegeEnt",collegeEnt);
        result.put("majorEnt",majorEnt);
        return new ResponseData(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMessage(), result);
    }
}
